import { defineStore } from 'pinia'
import { ref } from 'vue'
import type {
  UserVO,
  RegisterRequest,
  LoginRequest,
  LoginResult,
  UserInfoUpdateRequest,
} from '@/types'
import { authApi } from '@/api/auth'
import { useRouter } from 'vue-router'

export const useAuthStore = defineStore('auth', () => {
  const user = ref<UserVO | null>(null)
  const token = ref<string | null>(localStorage.getItem('token'))
  const router = useRouter()

  const register = async (data: RegisterRequest) => {
    try {
      const response = await authApi.register(data)
      if (response.data) {
        token.value = response.data.token
        localStorage.setItem('token', response.data.token)
      }
      return response
    } catch (error) {
      console.error('注册失败:', error)
      throw error
    }
  }

  const login = async (userName: string, password: string) => {
    try {
      console.log('userName:', userName)
      const response = await authApi.login({ userName, password })
      console.log('response:', response)
      if (response) {
        token.value = response.data.token
        localStorage.setItem('token', response.data.token)
      }
    } catch (error) {
      console.error('登录失败:', error)
      throw error
    }
  }

  const refreshToken = async () => {
    try {
      const response = await authApi.refreshToken()
      const data = response.data as LoginResult
      if (!data) {
        console.error('刷新Token失败:响应内容为空', response)
      }
      else if(data.tokenStatus == 4 && data.refreshToken){
        console.log('刷新Token成功:', data.refreshToken)
        localStorage.setItem('token', data.refreshToken)
        token.value = data.refreshToken
      }
      else if(data.tokenStatus != 99){
        console.log('刷新Token失败:tokenStatus:', data.tokenStatus)
        await logout()
      }
    } catch (error) {
      console.error('刷新Token失败:', error)
      throw error
    }
  }

  const logout = async () => {
    try {
      if (token.value) {
        await authApi.logout()
      }
    } catch (error) {
      console.error('登出失败:', error)
    } finally {
      user.value = null
      token.value = null
      localStorage.removeItem('token')
      router.push('/')
    }
  }

  const checkAuth = async () => {
    if (!token.value) return

    try {
      const response = await authApi.getCurrentUser()
      user.value = response.data
    } catch (error) {
      console.error('获取用户信息失败:', error)
      await logout()
    }
  }

  const checkUserNameExists = async (userName: string) => {
    try {
      const response = await authApi.checkUserName(userName)
      return response.data
    } catch (error) {
      console.error('检查用户名失败:', error)
      throw error
    }
  }

  const updateAvatar = async (avatar: string) => {
    try {
      const response = await authApi.updateAvatar(avatar)
      if (response.code === 200) {
        await checkAuth()
        return true
      }
      return false
    } catch (error) {
      console.error('更新头像失败:', error)
      return false
    }
  }

  const updateProfile = async (data: UserInfoUpdateRequest) => {
    try {
      const response = await authApi.updateUserInfo(data)
      if (response.code === 200) {
        await checkAuth()
        return true
      }
      return false
    } catch (error) {
      console.error('更新用户信息失败:', error)
      return false
    }
  }

  return {
    user,
    token,
    register,
    login,
    logout,
    checkAuth,
    checkUserNameExists,
    updateAvatar,
    updateProfile,
    refreshToken
  }
})
